package com.app.trafficclient.woDeZhangHu;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.app.trafficclient.R;
import com.app.trafficclient.util.MyLoadDialog;
import com.app.trafficclient.util.UserDao;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


public class MyAccount extends AppCompatActivity {
    Button sele, pay;
    ImageView bac;
    TextView txv, money;
    Spinner spinner;
    UserDao dao;
    EditText inputMoney;
    MyLoadDialog myLoadDialog;
    Context context;
    RequestQueue requestQueue;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //改布局： 账户余额过长是，文本框位置不齐，把账户余额和显示余额的分开！！！
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_account);

        initView();
        sendPostChaXun(); //进这个界面是，默认的是1号车，先加载一次他的余额
        initLisner();


    }

    private void sendPostChaXun() {
        /*
        * 用户名下小车余额查询：www.wpwh.info/user/query-car-balance
         请求参数：{"username":"user1","carId":1}
返回结果：
{
    "balance": 256,
    "id": 1,
    "status": 1,
    "statusInfo": "请求成功"
}
 */
       showAlertDialog();
        String url = "http://www.wpwh.info/user/query-car-balance";
        String car =spinner.getSelectedItem().toString();
        int carId = Integer.parseInt(car);

        Map<String,Object > map = new HashMap<String, Object>();
        map.put("username", "user1");
        map.put("carId",carId);

//        Log.d("map======》",map.toString());

        JSONObject jsonObject = new JSONObject(map);
        JsonRequest<JSONObject> jsonObjectJsonRequest = new JsonObjectRequest(Request.Method.POST, url,
                jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
              //  Log.d("cz1",jsonObject.toString());
                dismissdialog();
                String string = jsonObject.toString();
                Gson gson = new Gson();
                yueBean yueBean =gson.fromJson(string,yueBean.class);
                money.setText(String.valueOf(yueBean.getBalance()));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismissdialog();
                Toast.makeText(getApplicationContext(),"查询失败，请重试！",Toast.LENGTH_SHORT).show();
//                Log.d("cz1",volleyError.toString());
            }
        });
        requestQueue.add(jsonObjectJsonRequest);
    }

    private void sendPostChongZhi() {
        String url = "http://www.wpwh.info/user/recharge-car-balance";
        Map<String, String> map = new HashMap<>();
        map.put("username", "user1"); //改成登陆的账户
        map.put("car",spinner.getSelectedItem().toString());
        map.put("money",inputMoney.getText().toString().trim());
        Log.d("tag1",map.toString());
        JSONObject jsonObject = new JSONObject(map);
        JsonRequest<JSONObject> jsonObjectJsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
//                Log.d("cz1",jsonObject.toString());
                Toast.makeText(getApplicationContext(),"充值成功！",Toast.LENGTH_SHORT).show();
                dismissdialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismissdialog();
                Toast.makeText(getApplicationContext(),"充值失败，请重试！",Toast.LENGTH_SHORT).show();

//                Log.d("cz1",volleyError.toString());
            }
        });
        requestQueue.add(jsonObjectJsonRequest);
    }

    private void dismissdialog() {
        myLoadDialog.dismiss();
    }

    private void showAlertDialog() {
        myLoadDialog = new MyLoadDialog(context);
        myLoadDialog.setCanceledOnTouchOutside(false);
        myLoadDialog.show();
    }

    public void initView() {
        requestQueue = Volley.newRequestQueue(getApplicationContext());
        sele = findViewById(R.id.myaccount_sele);
        pay = findViewById(R.id.myaccount_pay);
        bac = findViewById(R.id.imageView_back);
        bac.setImageResource(R.drawable.change);
        txv = findViewById(R.id.tv_title);
        money = findViewById(R.id.account_money);  //显示余额
        spinner = findViewById(R.id.myaccount_spinner);
        inputMoney = findViewById(R.id.myaccount_inputMoney);  //输入充值金额
        txv.setText("我的账户");
        dao = new UserDao(MyAccount.this);
        context = MyAccount.this;
    }

    public void initLisner() {
        bac.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        sele.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendPostChaXun();
            }
        });

        pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputMoney.length() == 0 || Integer.parseInt(inputMoney.getText().toString()) == 0) {
                    Toast.makeText(MyAccount.this, "请核对金额\n只能输入1-999之间的数值!", Toast.LENGTH_LONG).show();
                    return;
                }
                showAlertDialog(); //显示延时
                //sqlite保存数据
                 dao.ins(
                          spinner.getSelectedItem().toString()//车号
                        , Integer.parseInt(inputMoney.getText().toString()) //充值金额
                        , "张三"//改成操作的账户
                        , System.currentTimeMillis());  //操作时间
                inputMoney.setText("");

                 sendPostChongZhi();

                }//onclick
        });

    }//initLisner


}
